package com.imooc.miaoshaproject.exceptions;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.NoHandlerFoundException;

import com.imooc.miaoshaproject.exceptions.ServiceException;
import com.imooc.miaoshaproject.exceptions.ErrorCodeEnum;
import com.imooc.miaoshaproject.response.R;

/**
 * 全局异常处理
 *
 * @author chenjianfei
 */
@ControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public R doError(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Exception ex) {
        ex.printStackTrace();
        Map<String, Object> responseData = new HashMap<>();
        if (ex instanceof ServiceException) {
            ServiceException serviceException = (ServiceException) ex;
            responseData.put("errCode", serviceException.getErrCode());
            responseData.put("errMsg", serviceException.getErrMsg());
        } else if (ex instanceof ServletRequestBindingException) {
            responseData.put("errCode", ErrorCodeEnum.UNKNOWN_ERROR.getErrCode());
            responseData.put("errMsg", "url绑定路由问题");
        } else if (ex instanceof NoHandlerFoundException) {
            responseData.put("errCode", ErrorCodeEnum.UNKNOWN_ERROR.getErrCode());
            responseData.put("errMsg", "没有找到对应的访问路径");
        } else {
            responseData.put("errCode", ErrorCodeEnum.UNKNOWN_ERROR.getErrCode());
            responseData.put("errMsg", ErrorCodeEnum.UNKNOWN_ERROR.getErrMsg());
        }
        return R.create(responseData, "fail");
    }
}
